package com.hongpu.service.impl;


import com.hongpu.domain.SysUser;
import com.hongpu.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义用户详情信息，用于从数据库中加载用户信息
 *
 * @author 张玉胜
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    SysUserMapper baseMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username != null) {
            SysUser sysUser = getSysUserByUseraccount(username);
            if (sysUser != null) {
                // 查询用户信息
                User user = new User(username, sysUser.getPassword(), Collections.emptyList());
                return user;
            }
        }
        return null;
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */

    public SysUser getSysUserByUseraccount(String account) {
        if (StringUtils.isEmpty(account)) {
            return null;
        }
        return baseMapper.ignoreTenantIdAndGetSysUserByUseraccount(account);
    }
}